var express = require('express');
var mysql = require('mysql');

let query = {
    search: 'select * from `menu` where sellerID=?',
    add: 'insert into `menu`(sellerID,cateName,menu) values (?,?,?,?,?,?,?,?,?)',
    del: 'delete from `menu` where sellerID=?',
    update: 'update `menu` set sellerID=?,cateName=?,menu=? where sellerID=?',
}
var search = function (sellerID,callback){
    //建立连接
    var connection = mysql.createConnection({
        host     : '148.70.88.72',
        user     : 'test',
        password : '5280d5e6515378d4',
        database : 'test'
    })
    //启动连接
    connection.connect(function (err){
        if(err)
            console.log(err);
    });
    connection.query(query.search,[sellerID], function (err, result) {
        if (err) throw err;
        //打印查询结果
        result[0].menuInfoStatus = 0;
        let tmpArr=result[0].menu.split("|")
        for(i=0,len=tmpArr.length;i<len;i++){
            tmpArr[i] = JSON.parse(tmpArr[i]);
        }
        result[0].dishes=tmpArr;
        result[0].cateName = result[0].cateName.split('|');
        //console.log(result[0]);
        callback(result);
        connection.end();
    })
}
var add = function (menu){
//建立连接
    var connection = mysql.createConnection({
        host     : '148.70.88.72',
        user     : 'test',
        password : '5280d5e6515378d4',
        database : 'test'
    })
    //启动连接
    connection.connect(function (err){
        if(err)
            console.log(err);
    });
    var arr = [];
    for(let i in menu){
        arr.push(menu[i]);
    }
    connection.query(query.add,arr, function (err, result) {
        if (err) throw err;
        connection.end();
    })

}
var del = function (sellerID){
//建立连接
    var connection = mysql.createConnection({
        host     : '148.70.88.72',
        user     : 'test',
        password : '5280d5e6515378d4',
        database : 'test'
    })
    //启动连接
    connection.connect(function (err){
        if(err)
            console.log(err);
    });
    connection.query(query.del,[sellerID], function (err, result) {
        if (err) throw err;
        connection.end();
    })
}
var update = function (order){
//建立连接
    var connection = mysql.createConnection({
        host     : '148.70.88.72',
        user     : 'test',
        password : '5280d5e6515378d4',
        database : 'test'
    })
    //启动连接
    connection.connect(function (err){
        if(err)
            console.log(err);
    });
    connection.query(query.update,[], function (err, result) {
        if (err) throw err;
        connection.end();
    })
}
exports.search = search;
exports.add = add;
exports.del = del;
exports.update = update;
